package com.cloudsail.domain.strategy.service.rule.chain.impl;

import com.cloudsail.domain.strategy.repository.IStrategyRepository;
import com.cloudsail.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.cloudsail.domain.strategy.service.rule.chain.factor.DefaultChainFactory;
import com.cloudsail.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author CloudSailNeverSee
 * @create 2024-10-22 19:50
 * @description 黑名单责任链
 */
@Slf4j
// 未该组件指定名称，方便我们将实例从map中取出来。(map依赖注入)
@Component("rule_blacklist")
public class BlackListLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    // 步骤二合一，过滤+抽奖。如果被接管，直接抽奖，传出奖品id
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        // 1.取出该抽奖策略对应的黑名单及其奖品id
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        Integer awardId = Integer.parseInt(splitRuleValue[0]);
        String[] blackList = splitRuleValue[1].split(Constants.SPLIT);
        // 2.判断该用户是否在黑名单中
        for (String blackUser : blackList) {
            if (blackUser.equals(userId)) {
                // 3.在黑名单中，则本次抽奖由规则引擎接管，返回特定奖品id。
                log.info("抽奖责任链-黑名单接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
                return DefaultChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModel())
                        // 写入默认配置黑名单奖品值 0.01 ~ 1 积分，也可以配置到数据库表中
                        .awardRuleValue("0.01,1")
                        .build();
            }
        }
        // 4.不在黑名单中，交给下一个链继续执行。
        log.info("抽奖责任链-黑名单放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return this.next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }
}
